package com.atguigu.jinx.job;


import com.atguigu.jinx.entity.dto.User;
import com.atguigu.jinx.mapper.UserMapper;
import com.atguigu.jinx.service.impl.TencentCosService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
@RequiredArgsConstructor
public class ClearUselessPicture {


    private final TencentCosService tencentCosService;

    final UserMapper userMapper;

    /**
     * 每天凌晨2点执行一次
     * cron表达式：秒 分 时 日 月 星期
     * 0 0 2 * * ? 表示每天的2:00:00执行
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void clearTask() {
        // 寻找出没有在数据库中被用户使用的图片的集合
        List<String> pictureUrls = tencentCosService.getFiles();
        List<String> existsUrls = userMapper.selectObjs(
                Wrappers.<User>lambdaQuery()
                        .select(true, User::getIconUrl)
                        .isNotNull(User::getIconUrl)
        );
        // 在保存图片的云存储中删除该图片的集合
        tencentCosService.deleteFile(generateShouldDeleteList(pictureUrls, existsUrls));
    }


    /**
     * 构造待删除图片
     *
     * @param pictureUrls 腾讯云cos存储照片路径
     * @param existsUrls  已存图片路径
     * @return 待删除图片路径集合
     */
    private List<String> generateShouldDeleteList(List<String> pictureUrls, List<String> existsUrls) {
        List<String> completedUrls = pictureUrls.stream()
                .filter(url -> !existsUrls.contains(url)).toList();
        return completedUrls;
    }
}
